package com.data.algorithm.search;

import java.util.ArrayList;
import java.util.List;

/**
 * 二分查找法
 *
 * @author wangjie
 * @version V1.0
 * @date 2020/3/30
 */
public class BinarySearch {


    public static void main(String[] args) {
        int[] arr = new int[]{1,1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20};
        List<Integer> resIndexList = binarySearch2(arr, 0, arr.length - 1, 1);
        System.out.println("resIndexList=" + resIndexList);
    }

    /**
     * 只找一个
     * @param arr
     * @param left
     * @param right
     * @param findVal
     * @return
     */
    public static int binarySearch(int[] arr, int left, int right, int findVal) {
        if (left > right) {
            return -1;
        } else {
            int mid = (left + right) / 2;
            int midVal = arr[mid];
            if (findVal > midVal) {
                return binarySearch(arr, mid + 1, right, findVal);
            } else {
                return findVal < midVal ? binarySearch(arr, left, mid - 1, findVal) : mid;
            }
        }
    }

    /**
     * 找到所有
     * @param arr
     * @param left
     * @param right
     * @param findVal
     * @return
     */
    public static List<Integer> binarySearch2(int[] arr, int left, int right, int findVal) {

        if (left > right) {
            return new ArrayList();
        } else {
            int mid = (left + right) / 2;
            int midVal = arr[mid];
            if (findVal > midVal) {
                return binarySearch2(arr, mid + 1, right, findVal);
            } else if (findVal < midVal) {
                return binarySearch2(arr, left, mid - 1, findVal);
            } else {
                List<Integer> resIndexlist = new ArrayList();

                int temp;
                for(temp = mid - 1; temp >= 0 && arr[temp] == findVal; --temp) {
                    resIndexlist.add(temp);
                }

                resIndexlist.add(mid);

                for(temp = mid + 1; temp <= arr.length - 1 && arr[temp] == findVal; ++temp) {
                    resIndexlist.add(temp);
                }

                return resIndexlist;
            }
        }
    }
}

